package com.heima.comment.filter;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Description:  拦截发送的请求，获取head中的 userId
 * @Version: V1.0
 */
@Slf4j
@Component
@Order(1)
@WebFilter(filterName = "appTokenFilter", urlPatterns = "/**")
public class AppTokenFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain) throws IOException, ServletException {

        //1 获取head
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String userId  =  servletRequest.getHeader("userId");

        //2 取用户id
        if (StringUtils.isNotBlank(userId) && Integer.valueOf(userId)!=0) {
            //3 id存到 TheadLocal 当前线程
            ApUser user = new ApUser();
            user.setId(Integer.valueOf(userId));
            AppThreadLocalUtils.setUser(user);
        }

        //4 放行
        filterChain.doFilter(servletRequest, response);
    }
}
